import 'dart:async';
import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/service/app_links_service.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/utils/string_externtion.dart';
import 'package:casdon/common/widget/badge_icon.dart';
import 'package:casdon/common/widget/common_banner_widget.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/core/utils/list_externtion.dart';
import 'package:casdon/core/utils/page_visibility_mixin.dart';
import 'package:casdon/modules/home/data/model/unified_device_model.dart';
import 'package:casdon/modules/home/providers/home_provider.dart';
import 'package:casdon/modules/home/ui/widget/my_device_card.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class HomeScreen extends ConsumerStatefulWidget {
  final appLinksService = AppLinksService();

  HomeScreen({super.key});

  @override
  ConsumerState<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends ConsumerState<HomeScreen>
    with
        SingleTickerProviderStateMixin,
        PageVisibilityMixin,
        WidgetsBindingObserver {
  bool _hasUnreadMessage = false;
  static const _nativeToolChannel = MethodChannel('native_tool');

  Future<void> _callNativeRnTool() async {
    try {
      await _nativeToolChannel.invokeMethod('openRnTool');
    } catch (e) {
      debugPrint('调用原生 openRnTool 失败: $e');
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void onPageVisible() {
    _onRefresh();
  }

  Future<void> _onRefresh() async {
    // 略微等待，确保有时间拉取
    if (ref.context.mounted) {
      await Future.delayed(const Duration(milliseconds: 300));
      // 触发刷新两个区域的数据
      ref.read(unifiedDeviceNotifierProvider.notifier).refresh();
      ref.read(homeBannerListNotifierProvider.notifier).refresh();
      _checkLatestMessage();
    }
  }

  @override
  Widget build(BuildContext context) {
    final bannerListState = ref.watch(homeBannerListNotifierProvider);
    final deviceListState = ref.watch(unifiedDeviceNotifierProvider);
    final double appBarHeight = MediaQuery.of(context).padding.top + 56.h;

    return buildPageVisibilityDetector(
      context,
      Scaffold(
        extendBodyBehindAppBar: true,
        backgroundColor: Colors.white,
        body: SafeArea(
          top: false,
          bottom: true,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Positioned.fill(
                child: Image.asset(
                  Assets.images.screenHeader.path,
                  fit: BoxFit.cover,
                  width: double.infinity,
                  alignment: Alignment.topCenter,
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: appBarHeight),
                child: RefreshIndicator(
                  color: context.colorScheme.primary,
                  onRefresh: _onRefresh,
                  child: SingleChildScrollView(
                    clipBehavior: Clip.none,
                    physics: const AlwaysScrollableScrollPhysics(
                      parent: BouncingScrollPhysics(),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        bannerListState.when(
                          loading: () => _buildSizedLoader(),
                          error: (e, _) => _buildSizedLoader(),
                          data: (state) {
                            final imgUrls = state.data
                                .map((e) => e.imageSrc.cropParams1000)
                                .toList();
                            final linkUrls = state.data
                                .map((e) => e.linkUrl)
                                .toList();
                            return _buildBanner(
                              imgUrls.takeFirstN(5),
                              linkUrls.takeFirstN(5),
                            );
                          },
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 12.w),
                          height: 32.h,
                          alignment: Alignment.centerLeft,
                          child: Row(
                            children: [
                              Text(
                                "我的设备",
                                style: TextStyle(
                                  fontSize: 16.r,
                                  fontWeight: FontWeight.normal,
                                ),
                              ),
                              const Spacer(),
                              BadgeIcon(
                                imagePath: Assets.images.icAddDevice.path,
                                onPressed: () {
                                  DeviceHomeRoute().push(context);
                                },
                              ),
                              GestureDetector(
                                onTap: () {
                                  DeviceHomeRoute().push(context);
                                },
                                child: Text(
                                  "添加设备",
                                  style: context.textTheme.bodyLarge!.copyWith(
                                    color: context.colorScheme.primary,
                                  ),
                                ),
                              ),
                              const SizedBox(width: 12),
                            ],
                          ),
                        ),
                        deviceListState.when(
                          loading: () => _buildLoadingWidget(),
                          error: (e, _) => _buildErrorWidget(''),
                          data: (data) {
                            final items = data.data;
                            if (items.isEmpty) {
                              return _buildEmptyWidget();
                            }
                            return Padding(
                              padding: EdgeInsets.only(
                                top: 12.h,
                                left: 12.w,
                                right: 12.w,
                              ),
                              child: Wrap(
                                spacing: 6.w,
                                runSpacing: 6.h,
                                children: List.generate(items.length, (index) {
                                  final cardWidth =
                                      (MediaQuery.of(context).size.width -
                                          12.w * 2 -
                                          6.w) /
                                      2;
                                  return SizedBox(
                                    width: cardWidth,
                                    child: GestureDetector(
                                      onTap: () => _handleDeviceTap(
                                        context,
                                        items[index],
                                      ),
                                      child: MyDeviceCard(model: items[index]),
                                    ),
                                  );
                                }),
                              ),
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                height: appBarHeight,
                child: _buildAppBar(context),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _handleDeviceTap(BuildContext context, UnifiedDeviceModel model) {
    if (model.devId != null) {
      TuyaService().gotoPanel(
        deviceId: model.devId!,
        pid: model.pid,
        fromType: PanelFromType.home,
      );
    }
  }

  Widget _buildAppBar(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(Assets.images.screenHeader.path),
          fit: BoxFit.cover,
          alignment: Alignment.topCenter,
        ),
      ),
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top,
        left: 16.w,
        right: 16.w,
        bottom: 12,
      ),
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: _callNativeRnTool,
            child: Text(
              '智能设备',
              style: context.textTheme.titleLarge!.copyWith(
                color: context.customColorThemeNonNull.textColor1,
              ),
            ),
          ),
          const Spacer(),
          BadgeIcon(
            imagePath: Assets.images.icScanner.path,
            onPressed: () {
              _goScannerPage(context);
            },
          ),
          SizedBox(width: 16.w),
          BadgeIcon(
            imagePath: Assets.images.icNotification.path,
            showBadge: _hasUnreadMessage,
            onPressed: () {
              _goNotificationPage(context);
            },
          ),
        ],
      ),
    );
  }

  Future<void> _checkLatestMessage() async {
    try {
      final ret = await TuyaService().getLatestMessage();
      if (mounted) {
        setState(() {
          _hasUnreadMessage = ret == true;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _hasUnreadMessage = false;
        });
      }
    }
  }

  Widget _buildLoadingWidget() => _buildSizedLoader();
  Widget _buildSizedLoader() {
    return const Center(
      child: SizedBox(
        width: 240,
        height: 240,
        child: Center(child: CommonLoadingWidget()),
      ),
    );
  }

  Widget _buildErrorWidget(String message) => Center(child: Text("加载失败"));

  Widget _buildEmptyWidget() {
    return SingleChildScrollView(
      physics: const BouncingScrollPhysics(),
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 40.h),
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(Assets.images.homeNoDevice.path),
              SizedBox(height: 12.h),
              Text(
                "马上去体验智能设备吧",
                style: TextStyle(color: Colors.black54, fontSize: 14.r),
              ),
              SizedBox(height: 20.h),
              GradientButton(
                text: "添加设备",
                gradientColors: [Color(0xFF9470FF), Color(0xFF6652F9)],
                borderRadius: 18,
                height: 36,
                width: 88,
                onPressed: () {
                  DeviceHomeRoute().push(context);
                },
              ),
              SizedBox(height: 20.h),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBanner(List<String> imageUrls, List<String> linkUrls) {
    if (imageUrls.isEmpty) return const SizedBox.shrink();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 12.h),
        CommonBannerWidget(
          imageUrls: imageUrls,
          height: 148.h,
          onTap: (index) {
            if (index < 0 || index >= linkUrls.length) return;
            final urlStr = linkUrls[index];
            if (urlStr.isEmpty) return;
            WebPageRoute(url: urlStr, title: '').push(context);
          },
        ),
        SizedBox(height: 24.h),
      ],
    );
  }

  void _goNotificationPage(BuildContext context) {
    Future.microtask(() {
      TuyaService().gotoMessage();
    });
  }

  void _goScannerPage(BuildContext context) {
    Future.microtask(() {
      if (context.mounted) {
        context.pushRoute(QRScannerRoute());
      }
    });
  }
}
